package ru.spies.dbfunctional;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.spies.dbwork.DBWork;
import ru.spies.entities.Role;
import ru.spies.entities.Siteuser;
import ru.spies.pages.ErrorPage;
import ru.spies.pages.GoodPage;

/**
 * Servlet implementation class UpdateUserInDB
 */
@WebServlet("/UpdateUserInDB")
public class UpdateUserInDB extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateUserInDB() {
        super();
    }


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Siteuser user = UpdateUserGetStep.getLastUser();
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		if (user==null) {
			out.print(ErrorPage.getInstance().getThisPage());
			return;
		}
		String userName =request.getParameter("newName");
		user.setUsername(userName);
		Role role = new Role();
		role.setParamForFindQuery(request.getParameter("newRole"));
		role = (Role) DBWork.getInstance().findObjectFromTable(role);
		if (role==null){
			out.print(ErrorPage.getInstance().getThisPage());
			return;
		}
		user.setRole(role);
		DBWork.getInstance().updateTableObject(user);
		out.print(GoodPage.getInstance().getThisPage());
	}

}
